import java.util.*;

public class Solution1 {
    public int[] elem;
    public int[] size;
    public long countPairs(int n, int[][] edges) {
        elem=new int[n];
        size=new int[n];
        for (int i = 0; i < n; i++) {
            elem[i]=i;
            size[i]=1;
        }
        for (int i = 0; i < edges.length; i++) {
            int pa=find(edges[i][0]);
            int pb=find(edges[i][1]);

            if(pa!=pb){
                elem[pa]=pb;
                size[pb]+=size[pa];
            }
        }

        long ans=0;
        long tol=0;
        for (int i = 0; i < n; i++) {
            if(elem[i]==i){
                ans+=size[i]*tol;
                tol+=size[i];
            }
        }

        return ans;
    }
    public int find(int x){
        if(elem[x]!=x){
            elem[x]=find(elem[x]);
        }
        return elem[x];
    }
}
